package com.zhousb.deviceManager.utils;

import com.zhousb.deviceManager.security.JwtUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import static com.zhousb.deviceManager.common.Constants.SUPER_ADMIN;

/**
 * @author JoinIn
 * @date 2023/9/7 10:42
 */

@Component
public class AuthUtils {

    public JwtUser getUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null && principal instanceof JwtUser) {
            return (JwtUser) principal;
        }
        return null;
    }

    public boolean isSuperAdmin(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null && principal instanceof JwtUser) {
            JwtUser jwtUser = (JwtUser) principal;
            return jwtUser.getRoles().stream().map(role->role.getRoleCode()).anyMatch(roleCode -> StringUtils.equals(SUPER_ADMIN, roleCode));
        }
        return false;
    }

    public PasswordEncoder passwordEncoder() {
       return new BCryptPasswordEncoder();
    }

}
